package iap.dao;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import iap.model.Order;

public class OrderDAOImpl implements OrderDAO {

	Connection connection;

	public OrderDAOImpl(Connection connection) {
		super();
		this.connection = connection;
	}

	@Override
	public void addNewOrder(Order order) {
		// TODO Auto-generated method stub
		String queryText = "INSERT INTO orders"
				+ "(p_orderid, charge, transaction_date) VALUES" + "(?,?,?)";

		try {
			PreparedStatement preparedStatement = connection
					.prepareStatement(queryText);
			preparedStatement.setInt(1, order.getId());
			preparedStatement.setInt(2, order.getCharge());
			preparedStatement.setDate(3, new Date(order.getTransactionDate()
					.getTime()));
			preparedStatement.executeUpdate();
			preparedStatement.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	public List<Order> getAllOrders() {
		ArrayList<Order> resultList = new ArrayList<Order>();
		String queryText = "SELECT * FROM orders;";
		ResultSet resultSet;
		Order order;
		try {
			Statement statement = connection.createStatement();
			resultSet = statement.executeQuery(queryText);
			while (resultSet.next()) {
				order = new Order();
				order.setId(resultSet.getInt(1));
				order.setCharge(resultSet.getInt(2));
				order.setTransactionDate(resultSet.getDate(3));
				resultList.add(order);
			}
			statement.close();
			resultSet.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out
				.println("We downloaded following number of orders from DB : "
						+ resultList.size());
		return resultList;
	}

}
